import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {reqUserLogin, reqUserRegister} from "../api/frontDesk/frontDeskApi";
import {message} from "antd";
import {getToken, setToken} from "../utils/token";

export const userLogin = createAsyncThunk(
    'user/userLoginStatus',
    async (userInfo) => {
        const data = await reqUserLogin(userInfo)
        return data
    }
)

export const userRegister = createAsyncThunk(
    'user/userRegisterStatus',
    async (userInfo) => {
        const data = await reqUserRegister(userInfo)
        return data
    }
)


export const userSlice = createSlice({
    name: 'user',
    initialState: {
        userAllInfo: {},
        web_token: getToken()
    },
    reducers: {
        //更新用户权限信息
        updateUserAllInfo(state, action) {
            state.userAllInfo.role = action.payload
        },
        //更新用户
        updateUser(state, action) {
            state.userAllInfo = action.payload
        },
        //清除用户信息
        clearUserAllInfo(state, action) {
            state.userAllInfo = {}
        }
    },
    extraReducers: builder => {
        //登录成功后的方法
        builder.addCase(userLogin.fulfilled, (state, action) => {
            const {status, token, user} = action.payload
            try {
                state.userAllInfo = {...user}
                state.web_token = token
                if (status !== 0) {
                    message.error("未找到该用户,请先进行注册!")
                } else if (status === 0) {
                    //设置token值
                    setToken(state.web_token)
                    message.info("用户登录成功了!")
                    window.location.reload()
                } else if (status === 400) {
                    message.info("手机号或密码输入有误!")
                }
            } catch (e) {
                message.error(e)
            }
        });
        builder.addCase(userRegister.fulfilled, (state, action) => {
            try {
                const {status} = action.payload
                if (status !== 0) {
                    message.error("手机号已经注册,请更换一个手机号!")
                } else {
                    //设置token值
                    message.success("注册成功!")
                }
            } catch (e) {
                message.error(e)
            }
        })
    }
})

export const {updateUserAllInfo, clearUserAllInfo} = userSlice.actions
export const {reducer: userReducer} = userSlice